import { createContext, useContext, useEffect } from "react"
import { useCookie, } from '@reactuses/core'
export type Theme = "dark" | "light" | "system"

type ThemeProviderProps = {
  children: React.ReactNode
  defaultTheme?: Theme
  storageKey?: string
}

type ThemeProviderState = {
  theme: Theme
  setTheme: (theme: Theme) => void
}

const initialState: ThemeProviderState = {
  theme: "system",
  setTheme: () => null,
}

const ThemeProviderContext = createContext<ThemeProviderState>(initialState)



export function ThemeProvider({
  children,
  defaultTheme = "system",
  storageKey = "app-ui-theme",
  ...props
}: ThemeProviderProps) {

  const [theme, setV, refresh] = useCookie('theme', {}, defaultTheme)
  useEffect(() => {
    if (!theme || theme === 'system') {
      document.documentElement.classList.remove('dark', 'light')
      document.documentElement.classList.add('system')
    } else {
      document.documentElement.classList.remove('system')
      document.documentElement.classList.toggle('dark', theme === 'dark')
      document.documentElement.classList.toggle('light', theme === 'light')
    }
  }, [theme])


  const value = {
    theme: theme as Theme,
    setTheme: (theme: Theme) => {
      console.log('setTheme', theme);

      setV(theme)
      refresh()
    },
  }

  return (
    <ThemeProviderContext.Provider {...props} value={value}>
      {children}
    </ThemeProviderContext.Provider>
  )
}

export const useTheme = () => {
  const context = useContext(ThemeProviderContext)

  if (context === undefined)
    throw new Error("useTheme must be used within a ThemeProvider")

  return context
}